package com.shujia.scala

import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}

object Demo24Jdbc {
  def main(args: Array[String]): Unit = {

    /**
     * 在scala语法中链接数据库
     *
     */
    //需要先在pom中增加mysql驱动的依赖
    //1、加载驱动
    Class.forName("com.mysql.jdbc.Driver")
    //2、建立数据库链接
    val con: Connection = DriverManager.getConnection("jdbc:mysql://192.168.129.201/bigdata?useUnicode=true&characterEncoding=UTF-8", "root", "123456")

    //3、编写sql查询数据
    val stat: PreparedStatement = con.prepareStatement("select * from students where clazz=?")

    //4、给参数赋值
    stat.setString(1, "文科六班")

    //5、执行查询
    val resultSet: ResultSet = stat.executeQuery()

    //6、解析数据
    while (resultSet.next()) {
      //通过列名取出数据
      val id: Long = resultSet.getLong("id")
      val name: String = resultSet.getString("name")
      val age: Long = resultSet.getLong("age")
      val gender: String = resultSet.getString("gender")
      val clazz: String = resultSet.getString("clazz")
      println(s"$id\t$name\t$age\t$gender\t$clazz")
    }

    //7、关闭链接
    stat.close()
    con.close()


  }

}
